/**
* This file is part of tictionary.
*
* tictionary is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* You should have received a copy of the GNU General Public License
* along with dev.clipall.  If not, see <http://www.gnu.org/licenses/>.
*
* http://code.google.com/p/tictionary/
*/

package dicterator.dictTreeCreator;

import dicterator.Constants;
import dicterator.Utils;
import dicterator.dict.Dict;
import dicterator.dict.Letter;
import dicterator.dict.LetterSet;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.StringTokenizer;

/**
 *
 * @author Erol Hira
 */
public class DictTreeCreator implements Constants{

    private File dictSourceFile;
    private Scanner scanner;

    public DictTreeCreator(){

        this(DICT_DB_FILE);
        
    }

    public DictTreeCreator(String dictSourceFile) {

        this.dictSourceFile = new File(dictSourceFile);

        try {
            scanner = new Scanner(this.dictSourceFile);
        } catch (FileNotFoundException ex) {
            ex.printStackTrace();
        }
    }

    //---------------------------------------------------------

    private void addWord(String word, String mean, Dict dict){

        LetterSet rootSet = dict.getRootSet();

        if(Character.isLetter(word.charAt(0)) && (Character.isDigit(word.charAt(0)) == false)){
            Letter w = addToTree(word, rootSet);
            w.setMean(mean);
        }
    }

    private Letter addToTree(String word, LetterSet rootSet){

        Letter letter = null;
        LetterSet letterSet = rootSet;

        for(int i = 0; i < word.length(); i++){
            letter = letterSet.forcedGiveLetter(word.charAt(i));

            if(i != word.length()-1){
                letterSet = letter.forcedGiveChildSet();
            }
        }

        return letter;
    }

    public Dict createDict(){

        Dict dict = new Dict();

        while(scanner.hasNextLine()){

            String line = scanner.nextLine();

            line = Utils.encodeAsUTF8(line);

            StringTokenizer token = new StringTokenizer(line, ":");


            String word = null;
            String mean = null;

            if(token.hasMoreTokens()){
                word = token.nextToken();
            }

            if(token.hasMoreTokens()){
                mean = token.nextToken();
            } else {
                mean = "a"; // finally try as ""
            }

            if(word != null){
                addWord(word, mean, dict);
            }
        }

        return dict;
    }

}
